package controllers;

import helpers.PaginatorHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import data.EmailData;

import entities.Email;

public class EmailListServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String q = (String) request.getParameter("q");
		
		int page = 1;
		int limit = 20;
		try {
			page = Integer.parseInt((String) request.getParameter("page"));
		} catch (Exception e) {}
		
		List<Email> emails = new ArrayList<Email>();
		
		if (q!= null && !q.isEmpty()) {
			Email email = EmailData.getByEmail(q);
			if (email != null) {
				emails.add(email);
			}
		} else {
			emails = EmailData.list(page, limit);
		}
		
		boolean nextPage = false;
		boolean prevPage = false;
		
		if (emails.size() == limit) {
			nextPage = true;
		}
		
		if (page > 1) {
			prevPage = true;
		}
		
		//Get paginate
		String queryString = request.getQueryString();
		String requestURI = request.getRequestURI();
		PaginatorHelper paginator = new PaginatorHelper(queryString);
		paginator.setUrl(requestURI);
		
		request.setAttribute("q", q);
		request.setAttribute("paginator", paginator);
		request.setAttribute("prevPage", prevPage);
		request.setAttribute("nextPage", nextPage);
		request.setAttribute("emails", emails);
		request.setAttribute("page", page);
		try {
			request.getRequestDispatcher("/pages/email_list.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}
